package leetcode;

public class Zigzag_conversion {

}

class Solution6 {
    public String convert(String s, int numRows) {
    	String result = new String();
        if(numRows == 1) return s;
    	for (int i = 0; i < s.length(); i += (2*numRows-2)) {
			result += s.charAt(i);
		}
    	if(numRows > 2) {
    		for (int i = 1; i < numRows-1; i++) {
    			for (int j = i; j < s.length(); j += (2*numRows-2)) {
    				result += s.charAt(j);
    				try {
        				result += s.charAt(j+(2*numRows-2)-2*i);
					} catch (StringIndexOutOfBoundsException e) {
						// TODO: handle exception
					}
    			}
    		}
    	}
    	for (int i = numRows-1; i < s.length(); i += (2*numRows-2)) {
			result += s.charAt(i);
		}
    	return result;
    }
    
    public String converts(String s, int numRows) {
    	StringBuilder result = new StringBuilder();
        if(numRows == 1) return s;
    	for (int i = 0; i < s.length(); i += (2*numRows-2)) {
			result.append(s.charAt(i));
		}
    	if(numRows > 2) {
    		for (int i = 1; i < numRows-1; i++) {
    			for (int j = i; j < s.length(); j += (2*numRows-2)) {
    				result.append(s.charAt(j));
    				try {
        				result.append(s.charAt(j+(2*numRows-2)-2*i));
					} catch (StringIndexOutOfBoundsException e) {
						// TODO: handle exception
					}
    			}
    		}
    	}
    	for (int i = numRows-1; i < s.length(); i += (2*numRows-2)) {
			result.append(s.charAt(i));
		}
    	return result.toString();
    }
}
